package com.example.iqiyitest.view;

import com.example.iqiyitest.R;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;


public class DurianLoading extends RelativeLayout {  
  
    private AnimationDrawable frameAnimation;//创建帧动画的对象  
    private ImageView loadingImg;//加载图片  
    Context mContext;
    public DurianLoading(Context context) {  
        super(context);  
        initView(context);  
    }
  
    public DurianLoading(Context context, AttributeSet attrs) {  
        super(context, attrs);  
        initView(context);  
    }  
      
    /** 
     * 布局中的图片和文字是通过动态加载的方式处理的 
     */  
    private void initView(Context context) {  
        mContext = context;  
        LayoutParams imgLp = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,  
                ViewGroup.LayoutParams.WRAP_CONTENT);  
        imgLp.addRule(RelativeLayout.CENTER_HORIZONTAL);//设置图片水平居中  
        loadingImg = new ImageView(context);  
        loadingImg.setId(Integer.parseInt("1"));//给loadingImg设置一个坐标，可以作为下面空间的参考位置  
        loadingImg.setLayoutParams(imgLp);  
        addView(loadingImg);  
  
        LayoutParams textLp = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,  
                ViewGroup.LayoutParams.WRAP_CONTENT);  
        textLp.addRule(RelativeLayout.CENTER_IN_PARENT);  
        textLp.addRule(RelativeLayout.BELOW, loadingImg.getId());  
        hideLoadUi();  
    }  
  
    /** 
     * 显示加载动画 
     * @param isStopAnim 是否需要停止动画 
     */  
    public void showLoadUi() {  
        setVisibility(View.VISIBLE);  
        //给图片设置加载动画  
        loadingImg.setBackgroundResource(R.drawable.loading);  
        frameAnimation = (AnimationDrawable) loadingImg.getBackground();  
        //启动动画  
        frameAnimation.start();  
    }
    
    public void hideLoadUi(){
    	setVisibility(View.GONE);  
        if (frameAnimation != null) {  
            if (frameAnimation.isRunning()) {  
                frameAnimation.stop();  
            }  
        }  
    }
  
    /** 
     * 释放资源 
     * 在destroy或者destroy view的时候调用 
     */  
    public void release() {  
        if (frameAnimation != null && frameAnimation.isRunning()) {  
            frameAnimation.stop();  
        }  
        frameAnimation = null;  
        if (loadingImg != null) {  
            loadingImg.setImageDrawable(null);  
        }  
    }  
}  